/*
 * @Author: your name
 * @Date: 2021-07-08 17:21:20
 * @LastEditTime: 2021-07-08 17:59:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \yuyunbook\src\utils\request.ts
 */
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: '',
  timeout: 60000
})

// 请求拦截
service.interceptors.request.use((config: AxiosRequestConfig) => {
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use((response: AxiosResponse) => {
  const res = response.data
  if (res.code !== 200) {
    ElMessage.error(res.message)
    if (res.code === 5000) {
      // 重新登录并刷新页面
      location.reload()
    }

    return Promise.reject(res.message || 'Error')
  } else {
    return res
  }
}, error => {
  console.log('err' + error)
  ElMessage.error(error.message)
  return Promise.reject(error)
})
